package com.zj.leetcode.medium.tree;

/**
 * @program: algorithm
 * @description: 在二叉树中增加一行
 * 623 add-one-row-to-tree
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class AddOneRowToTree {
    public static void main(String[] args) {
        Solution solution = new AddOneRowToTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {

        public TreeNode addOneRow(TreeNode root, int v, int d) {

            if (root == null) {
                return null;
            }

            if (d == 1) {

                TreeNode newRoot = new TreeNode(v);
                newRoot.left = root;
                return newRoot;
            }

            if (d == 2) {

                TreeNode l = new TreeNode(v), r = new TreeNode(v);
                l.left = root.left;
                r.right = root.right;
                root.left = l;
                root.right = r;

                return root;
            }

            root.left = addOneRow(root.left, v, d - 1);
            root.right = addOneRow(root.right, v, d - 1);

            return root;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}